import DefaultImage from '@/asset/default-image.png';
import ErrorComp from '@/components/common/error-comp';
import LeftToRightView from '@/components/common/motion/left-to-right-view';
import OrderStatus from '@/components/common/order-status';
import QueryImage from '@/components/common/query-image';
import { Button } from '@/components/ui/button';
import CancelOrder from '@/components/user/cancel-order';
import EvaluateOrder from '@/components/user/evaluate-order';
import PayOrder from '@/components/user/pay-order';
import { getOrderById } from '@/service/query/order';
import { getProductsByIds } from '@/service/query/product';
import dayjs from 'dayjs';
import Link from 'next/link';
import { z } from 'zod';

export const metadata = {
  title: '订单详情',
};

const paramSchema = z.object({
  id: z.coerce.number().int().positive(),
});

export default async function Page({
  params,
}: { params: Promise<{ id: string }> }) {
  const paramsRes = paramSchema.safeParse(await params);
  if (!paramsRes.success)
    return <ErrorComp message="参数错误" backPath="/order" />;

  const { result: orderData, error } = await getOrderById(paramsRes.data.id);
  if (error) return <ErrorComp message={error.message} backPath="/order" />;

  const { result: productsData, error: productsError } = await getProductsByIds(
    orderData.products.map((p) => p.id),
  );

  return (
    <div className="bg-muted">
      <LeftToRightView>
        <div className="pt-12 bg-muted ">
          <div className="relative h-32 top-16 px-16 flex items-start justify-between">
            <Link href="/order" className="flex items-center group text-sm">
              <span className="i-ri-arrow-left-s-line group-hover:-translate-x-1 transition-all duration-300" />
              返回订单列表
            </Link>
            <OrderStatus order={orderData} />
          </div>
          <div className="space-y-8 py-10 px-16 min-h-screen shadow-lg bg-background relative z-10 rounded-t-3xl">
            <Link
              href={`/detail-shop/${orderData.shop.id}`}
              className="text-2xl font-bold group flex items-center"
            >
              {orderData.shop.name}
              <span className="i-ri-arrow-right-s-line opacity-0 group-hover:opacity-100 group-hover:translate-x-1 transition-all" />
            </Link>
            <div className="space-y-5">
              {productsError ? (
                <div className="text-center py-10">{productsError.message}</div>
              ) : (
                orderData.products.map(({ id, count }) => {
                  const product = productsData.find((p) => p.id === id);
                  if (!product) return null;
                  return (
                    <div key={id} className="flex justify-between items-center">
                      <div className="flex items-end gap-4">
                        <QueryImage
                          imageKey={product.imageKeys[0]}
                          defaultImage={DefaultImage}
                          wrapperClassName="rounded-lg w-32 h-16 shrink-0"
                          imgClassName="object-cover w-full h-full rounded-lg"
                        />
                        <span className="text-nowrap">x {count}</span>
                      </div>
                      <div className="space-y-1">
                        <div>{product.name}</div>
                        <div className="text-end">
                          ￥{count * Number(product.price)}
                        </div>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
            {!productsError && (
              <div className="text-xl font-bold">
                总价：
                {Math.round(
                  orderData.products.reduce((total, { id, count }) => {
                    const product = productsData.find((p) => p.id === id);
                    if (!product) return total;
                    return total + count * Number(product.price);
                  }, 0) * 100,
                ) / 100}
                元
              </div>
            )}
            <div className="flex justify-center gap-5">
              {orderData.status === 'completed' && (
                <EvaluateOrder
                  evaluation={orderData.evaluation}
                  orderId={orderData.id}
                />
              )}
              {['unpaid', 'unaccepted'].includes(orderData.status) && (
                <CancelOrder orderId={orderData.id} />
              )}
              <Link href={`/message/${orderData.shop.userId}`}>
                <Button variant="outline">联系商家</Button>
              </Link>
              {orderData.status === 'unpaid' && (
                <PayOrder orderId={orderData.id} />
              )}
            </div>
            <div className="text-sm space-y-2">
              {[
                {
                  label: '订单编号: ',
                  value: orderData.id,
                },
                {
                  label: '收货地址: ',
                  value: orderData.address,
                },
                {
                  label: '联系人: ',
                  value: orderData.userName,
                },
                {
                  label: '联系电话: ',
                  value: orderData.userPhone,
                },
                {
                  label: '下单时间: ',
                  value: dayjs(orderData.createdAt).format(
                    'YYYY-MM-DD HH:mm:ss',
                  ),
                },
                {
                  label: '备注: ',
                  value: orderData.remark ?? '无',
                },
              ].map((item) => (
                <div className="flex items-center relative" key={item.label}>
                  <div>{item.label}</div>
                  <div className="absolute left-24">{item.value}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </LeftToRightView>
    </div>
  );
}
